//
//  KZUserMyNewWordVC.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/9/4.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZUserMyNewWordVC.h"

// vc
#import "KZVocabularyImproveMakeTestVC.h"

// view
#import "DicMainView.h"

// api
#import "KZVocabularyImproveNetApi.h"

// model
#import "KZVocabularyPackageModel.h"

@interface KZUserMyNewWordVC () <UITableViewDelegate, UITableViewDataSource>


@property (nonatomic, assign) int sortType;         // 0:日期，1:首字母

@property (nonatomic, copy  ) NSArray *items;       // 全部

@property (nonatomic, copy  ) NSArray *indexTitles; // 右侧首字母索引
@property (nonatomic, copy  ) NSArray *indexItems;  // 按首字母排序的数组(二维)

@property (nonatomic, copy  ) NSArray *dateTitles;  // 右侧首字母索引
@property (nonatomic, copy  ) NSArray *dateItems;   // 按首字母排序的数组(二维)



@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) UIView *emptyView;

@end

@implementation KZUserMyNewWordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"我的生词本";
    [self addLeftBackBarButtonItem];
    [self setupNaviUI];
    [self createTableView];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self getVocabularyBuilder];
}

#pragma mark - Net
// 获取我的生词本
- (void)getVocabularyBuilder {
    
    [MBProgressHUD showLoadind:@"正在加载生词本，请稍候..."];
    KZVocabularyImproveNetApi *api = [KZVocabularyImproveNetApi new];
    api.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,};
    [api getVocabularyBuilder:^(NSArray *items) {
        [MBProgressHUD hideHud];
        self.items = items;
        [self sortByDate];
        [self.table reloadData];
        
        // 没有生词不能点击
        if (items.count == 0) {
            [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.equalTo(@0);
            }];
            self.table.backgroundView = self.emptyView;
        } else {
            [self.bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(H(60));
            }];
            self.table.backgroundView = UIView.new;
        }

    } failuer:^(NSString *error) {
        [MBProgressHUD showFailureWithText:error];
    }];
}

// 获取听说词汇包信息
- (void)getUnfamiliarVocabularyPackage {
    
    [MBProgressHUD showLoadind:@"正在查询待下一生词包，请稍候..."];
    
    KZVocabularyImproveNetApi *api = [KZVocabularyImproveNetApi new];
    api.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,};
    [api getUnfamiliarVocabularyPackage:^(KZVocabularyPackageModel *model) {
        
        [MBProgressHUD hideHud];
        
        if (!model) {
            return;
        }
        if (model.currentPackage.Detail.count == 0) {
            [MBProgressHUD showFailureWithText:@"没有需要训练的生词了！"];
            return;
        }
        
        KZVocabularyImproveMakeTestVC_version2 *vc = [KZVocabularyImproveMakeTestVC_version2 new];
        vc.type = KZVocabularyTypeUnfamiliar;
        vc.packageModel = model;
        [self.navigationController pushViewController:vc animated:true];
        
    } failuer:^(NSString *error) {
        [MBProgressHUD showFailureWithText:error];
    }];
}

#pragma mark - 创建视图
- (void)setupNaviUI {
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 30, 30);
    [button setImage:[UIImage imageNamed:@"kz-时间排序"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"kz-字母排序"] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(sortChange:) forControlEvents:UIControlEventTouchUpInside];
    [button setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [self addCustomItemviews:@[button] position:ByNavigationItemPositionModeRight];
}
- (void)createTableView {
    
    _bottomView = [UIView new];
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(@0);
        }
        make.height.mas_equalTo(H(0));
    }];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = 666;
    button.titleLabel.font = FONT(15);
    [button setTitle:@"生词听说训练" forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"kz-生词强化训练背景"] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(gotoUnfamiliarTrain) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(W(15));
        make.right.mas_equalTo(W(-15));
        make.top.mas_equalTo(W(10));
        make.bottom.mas_equalTo(W(-10));
    }];
    
    self.table = [[UITableView alloc] init];
    self.table.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    self.table.separatorColor = [UIColor colorWithWhite:0.9 alpha:1];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(@0);
        make.bottom.equalTo(_bottomView.mas_top);
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (_sortType == 0) {
        return _dateItems.count;
    } else {
        return _indexItems.count;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *temp;
    if (_sortType == 0) {
        temp = _dateItems[section];
    } else {
        temp = _indexItems[section];
    }
    
    return temp.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.textLabel.font = FONT(15);
    }
    NSArray *temp;
    if (_sortType == 0) {
        temp = _dateItems[indexPath.section];
    } else {
        temp = _indexItems[indexPath.section];
    }
    KZVocabularyCurrentPackageDetailModel *model = temp[indexPath.row];
    cell.textLabel.text = model.Vocabulary;
    
    return cell;
}
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    return _sortType == 0 ? nil : _indexTitles;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 25;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *header = [UIView new];
    header.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].scale == 2 ? 15: 15, 0, 100, 25)];
    label.font = FONT(14);
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor lightGrayColor];
    [header addSubview:label];
    
    NSString *text;
    if (_sortType == 0) {
        text = _dateTitles[section];
    } else {
        text = _indexTitles[section];
    }
    label.text = text;
    return header;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:false];
    
    NSArray *temp;
    if (_sortType == 0) {
        temp = _dateItems[indexPath.section];
    } else {
        temp = _indexItems[indexPath.section];
    }
    KZVocabularyCurrentPackageDetailModel *model = temp[indexPath.row];
    
    DicMainView *main = [[DicMainView alloc] initWithTestType:DictTestType_Word isShowRecord:YES];
    main.dictUrl = [NSString stringWithFormat:@"%@api/ZXYYTS/W_ZXYYTS_GetCoursewareByCode",KGetUserDefaults(@"SystemIP")];
    main.dictParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                       @"schoolId":DR_UserInfo.SchoolID,
                       @"stuId":DR_UserInfo.UserID,
                       @"knowledge": model.VocabularyID,
                       @"levelCode": KGetUserDefaults(@"TestLayer")
                       };
    [main popAnimated:YES];
}

#pragma mark - 事件
- (void)sortChange:(UIButton *)button {

    button.selected = !button.selected;
    _sortType = (int)button.selected;
    _sortType == 0 ? [self sortByDate] : [self sortByInitial];
    [_table reloadData];
}
- (void)gotoUnfamiliarTrain {
    
    [self getUnfamiliarVocabularyPackage];
}

#pragma mark - 辅助方法
// 按首字母排序
- (void)sortByInitial {
    
    _sortType = 1;
    
    _items = [_items sortedArrayUsingComparator:^NSComparisonResult(KZVocabularyCurrentPackageDetailModel *model1, KZVocabularyCurrentPackageDetailModel *model2) {
        if ([model1.Vocabulary characterAtIndex:0] < [model2.Vocabulary characterAtIndex:0]) {
            return NSOrderedAscending;
        } else {
            return NSOrderedDescending;
        }
    }];
    
    
    NSMutableArray *indexTitles = @[].mutableCopy;
    NSMutableArray *indexItems = @[].mutableCopy;
    
    for (int i = 0; i < _items.count; i ++) {
        KZVocabularyCurrentPackageDetailModel *model = _items[i];
        NSString *intital = [[model.Vocabulary substringWithRange:NSMakeRange(0, 1)] uppercaseString];
        if (![indexTitles containsObject:intital]) {
            [indexTitles addObject:intital];
            NSMutableArray *temp = [NSMutableArray new];
            [indexItems addObject:temp];
            [temp addObject:model];
        } else {
            NSInteger index = [indexTitles indexOfObject:intital];
            NSMutableArray *temp = indexItems[index];
            [temp addObject:model];
        }
    }
    
    
    _indexTitles = indexTitles.copy;
    _indexItems = indexItems.copy;
}
// 按日期排序
- (void)sortByDate {
    
    _sortType = 0;
    
    // 先排序
    _items = [_items sortedArrayUsingComparator:^NSComparisonResult(KZVocabularyCurrentPackageDetailModel *model1, KZVocabularyCurrentPackageDetailModel *model2) {
        if ([model1.UpdateTime timeIntervalSince1970] > [model2.UpdateTime timeIntervalSince1970]) {
            return NSOrderedAscending;
        } else {
            return NSOrderedDescending;
        }
    }];
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    cal.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:8];
    NSDateComponents *todayCom = [cal components:(NSCalendarUnitDay | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
    
    NSMutableArray *dateTitles = @[].mutableCopy;
    NSMutableArray *dateItems = @[].mutableCopy;
    for (int i = 0; i < _items.count; i ++) {
        KZVocabularyCurrentPackageDetailModel *model = _items[i];
        NSDateComponents *dateCom = [cal components:(NSCalendarUnitDay | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:model.UpdateTime];
        NSLog(@"kz:%.0lf", [model.UpdateTime timeIntervalSince1970]);
        NSString *dateStr = [NSString stringWithFormat:@"%lu-%lu-%lu", dateCom.year, dateCom.month, dateCom.day];
        // 今天
        if (todayCom.year == dateCom.year &&
            todayCom.month == dateCom.month &&
            todayCom.day == dateCom.day) {
            
            dateStr = @"今天";
        }
        
        if (![dateTitles containsObject:dateStr]) {
            [dateTitles addObject:dateStr];
            NSMutableArray *temp = [NSMutableArray new];
            [dateItems addObject:temp];
            [temp addObject:model];
        } else {
            NSInteger index = [dateTitles indexOfObject:dateStr];
            NSMutableArray *temp = dateItems[index];
            [temp addObject:model];
        }
    }
    
    
    _dateTitles = dateTitles.copy;
    _dateItems = dateItems.copy;
}

#pragma mark - getter
- (UIView *)emptyView {
    
    if (!_emptyView) {
        _emptyView = [[UIView alloc] initWithFrame:self.table.bounds];
        
        UIImageView *imageView = [UIImageView new];
        imageView.image = [UIImage imageNamed:@"kz-暂无数据"];
        [_emptyView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_emptyView);
        }];
    }
    return _emptyView;
}
@end
